<?php
/**
 * payment.php
 * This file is called after the user clicks on a button during
 * the Pay process to use PayPal's AdaptivePayments Pay features'. The
 * user logs in to their PayPal account.
 * Called by Pay.php
 */
$path = basePath() . '/include/paypal/lib/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once('services/AdaptivePayments/AdaptivePaymentsService.php');
require_once('PPLoggingManager.php');
require_once('Common/Constants.php');

define("DEFAULT_SELECT", "- Select -");

function addReceiver($receiverEmail, $receiverAmount, $primaryReceiver, $invoiceId = "", $paymentType = "", $paymentSubType = "", $phoneCountry = "", $phoneNumber = "", $phoneExtn = "") {
	$receiver = new Receiver();
	$receiver->email = $receiverEmail;
	$receiver->amount = $receiverAmount;
	$receiver->primary = $primaryReceiver;
	
	if(invoiceId != "") {
		$receiver->invoiceId = $invoiceId;
	}
	if($paymentType != "" && $paymentType != DEFAULT_SELECT) {
		$receiver->paymentType = $paymentType;
	}
	if($paymentSubType != "") {
		$receiver->paymentSubType = $paymentSubType;
	}
	if($phoneCountry != "" && $phoneNumber) {
		$receiver->phone = new PhoneNumberType($phoneCountry, $phoneNumber);
		if($phoneExtn != "") {
			$receiver->phone->extension = $phoneExtn;
		}
	}
	
	return $receiver;
}

//returns paykey or false depending on if credit was transfered
function buy_credits ($user_id, $credits, $amount, $url = "http://206.76.99.249/campus/") {
	$receiver = array();
	$receiver[0] = addReceiver("john_1351896111_biz@utexas.edu", $amount, false);
	$receiverList = new ReceiverList($receiver);
	$payRequest = new PayRequest(new RequestEnvelope("en_US"), "PAY", $url . "buy.php", "USD", $receiverList, $url . "confirm/?user_id=$user_id&credits=$credits");
	$service = new AdaptivePaymentsService();
	try {
		$response = $service->Pay($payRequest);
	} catch(Exception $ex) {
		require_once 'Common/Error.php';
		exit;
	}
	$ack = strtoupper($response->responseEnvelope->ack);
	if($ack != "SUCCESS") {
		return false;
	}
	$payKey = $response->payKey;
	return $payKey;	
}


function buy_item ($item_id, $buyer_id, $seller_id, $amount, $url = "http://206.76.99.249/campus/") {
	$receiver = array();
	$receiver[0] = addReceiver("john_1351896111_biz@utexas.edu", $amount, false);
	$receiverList = new ReceiverList($receiver);
	$payRequest = new PayRequest(new RequestEnvelope("en_US"), "PAY", $url . "item/detail.php?item_id=$item_id", "USD", $receiverList, $url . "confirm/?item_id=$item_id&buyer_id=$buyer_id");
	$service = new AdaptivePaymentsService();
	try {
		$response = $service->Pay($payRequest);
	} catch(Exception $ex) {
		require_once 'Common/Error.php';
		exit;
	}
	$ack = strtoupper($response->responseEnvelope->ack);
	if($ack != "SUCCESS") {
		return false;
	}
	$payKey = $response->payKey;
	return $payKey;	
}
